package cn.shengchao.examstar.ai.domain.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.ai.acl.ports.IKnowledgePointService;
import cn.shengchao.examstar.ai.domain.valueobject.SpecificationType;
import cn.shengchao.examstar.ai.domain.valueobject.UserId;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePoint;
import cn.shengchao.examstar.product.acl.ports.repositories.ISpecificationTypeRepository;
import cn.shengchao.examstar.product.infrastructure.dao.po.TSpecificationType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class KnowledgeDomainServiceImpl implements KnowledgeDomainService {

    private final ISpecificationTypeRepository specificationTypeRepository;
    private final IKnowledgePointService knowledgePointService;

    @Override
    public String getHierarchicalSpecificationTypeName(SpecificationType specificationTypeId) {
        try {
            Long typeId = specificationTypeId.getValue();
            List<TSpecificationType> currentTypeList = specificationTypeRepository.getSpecificationTypesByIdList(List.of(typeId));
            if (CollectionUtils.isEmpty(currentTypeList)) {
                log.error("未找到指定类目: {}", typeId);
                return "未知类目";
            }
            TSpecificationType currentType = currentTypeList.getFirst();
            if (StrUtil.isBlank(currentType.getPath())) {
                return getSpecificationTypeNamesByRecursion(typeId);
            }
            String path = currentType.getPath();
            log.info("类目ID: {}, path: {}", typeId, path);
            List<Long> pathIds = new ArrayList<>();
            String[] segments = path.split("/");
            for (String segment : segments) {
                if (StrUtil.isNotBlank(segment)) {
                    pathIds.add(Long.parseLong(segment.trim()));
                }
            }
            if (!pathIds.contains(typeId)) {
                pathIds.add(typeId);
            }
            List<TSpecificationType> specificationTypes = specificationTypeRepository.getSpecificationTypesByIdList(pathIds);
            StringBuilder result = new StringBuilder();
            for (Long id : pathIds) {
                for (TSpecificationType type : specificationTypes) {
                    if (id.equals(type.getId())) {
                        result.append(type.getName());
                        break;
                    }
                }
            }
            return result.toString();
        } catch (Exception e) {
            log.error("构建类目层级名称失败", e);
            return "未知类目";
        }
    }

    private String getSpecificationTypeNamesByRecursion(Long specificationTypeId) {
        try {
            List<String> categoryNames = new ArrayList<>();
            Long currentId = specificationTypeId;
            while (currentId != null && currentId > 0) {
                List<TSpecificationType> types = specificationTypeRepository.getSpecificationTypesByIdList(List.of(currentId));
                if (CollectionUtils.isEmpty(types)) {
                    break;
                }
                TSpecificationType currentType = types.getFirst();
                categoryNames.addFirst(currentType.getName());
                currentId = currentType.getParentId();
            }
            return String.join("", categoryNames);
        } catch (Exception e) {
            log.error("递归构建类目层级名称失败", e);
            return "未知类目";
        }
    }

    @Override
    public String getKnowledgeLeafNodeNames(UserId userId, SpecificationType specificationTypeId) {
        List<KnowledgePoint> knowledgePoints = getKnowledgePoints(specificationTypeId.getValue());
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            return "";
        }
        return knowledgePoints.stream()
                .map(KnowledgePoint::getName)
                .collect(Collectors.joining("、"));
    }

    @Override
    public String getKnowledgeLeafNodesAsJson(UserId userId, SpecificationType specificationTypeId) {
        List<KnowledgePoint> knowledgePoints = getKnowledgePoints(specificationTypeId.getValue());
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            return "[]";
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (KnowledgePoint point : knowledgePoints) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("id", point.getId().toString());
            pointMap.put("name", point.getName());
            result.add(pointMap);
        }
        return JSONUtil.toJsonStr(result);
    }

    private List<KnowledgePoint> getKnowledgePoints(Long typeId) {
        List<KnowledgePoint> leafNodes = knowledgePointService.getKnowledgeLeafNodesBySpecificationType(typeId);
        if (!CollectionUtils.isEmpty(leafNodes)) {
            return leafNodes;
        }
        log.warn("类目[{}]没有找到叶子知识点，尝试返回全部知识点", typeId);
        return knowledgePointService.getKnowledgePointsBySpecificationType(typeId);
    }
}